import React from 'react';
import styles from './index.less';
import moment from 'moment';
import { connect } from 'umi';
// components
import { Spin, Input, Button, Space } from 'antd';
import ReactMarkdown from 'react-markdown';
import { TRDefault, TRMessage } from '#/components';
// api
import { HttpCode } from '#/utils/contacts';
import { fetchFile, upLoadFile, deleteFile } from '@/services/annex';
import { getFileLogId, saveFileLogId } from './services';

const UpdateLog = ({ buttonPermissions }) => {
  const canEdit = buttonPermissions.some((x) => x.menuCode === 'EditUpdateLog');
  const [loading, setLoading] = React.useState(true);
  const [fileId, setFileId] = React.useState('');
  const [md, setMd] = React.useState('');

  React.useEffect(() => {
    fetch();
  }, []);

  const fetch = async () => {
    setLoading(true);
    const res = await getFileLogId();
    const _id = res?.data?.fileId || '';
    setFileId(_id);
    if (!_id) {
      setLoading(false);
      return;
    }
    let file = await fetchFile(_id);
    if (typeof file !== 'string') {
      try {
        file = JSON.stringify(file);
      } catch (error) {}
    }
    setLoading(false);
    setMd(file);
  };

  const onAdd = () => {
    setMd(`
# [version] - ${moment().format('YYYY-MM-DD hh:mm:ss')}
## 新增
* 新增了xxx
* 新增了xxx
## 优化
* 优化了xxx
* 优化了xxx
## 删除
* 删除了xxx
* 删除了xxx
${md}`);
  };

  const onSave = async () => {
    setLoading(true);
    const id_old = (await getFileLogId())?.data?.fileId || fileId;
    // 上传
    const _file = new Blob([md], { type: 'text/plain;charset=utf-8' });
    const res = await upLoadFile(_file, 'etrade_deal_update_log');
    const id_new = res?.uploadBody?.fileId;
    if (!id_new) {
      setLoading(false);
      return TRMessage.error('保存失败');
    }
    // 保存
    const res2 = await saveFileLogId(id_new);
    if (res2?.statusCode !== HttpCode.SUCCESS) {
      deleteFile(id_new);
      setLoading(false);
      return TRMessage.error('保存失败');
    }
    setLoading(false);
    TRMessage.success('保存成功');
    setFileId(id_new);
    // 删旧日志
    id_old && deleteFile(id_old);
  };

  return (
    <Spin wrapperClassName={styles.con} spinning={loading}>
      {canEdit && (
        <div className={styles.head}>
          <Space size={16}>
            <Button onClick={onAdd}>新增一条</Button>
            <Button onClick={onSave}>保存</Button>
          </Space>
        </div>
      )}
      <div className={styles.main}>
        {canEdit && (
          <div className={styles.editor}>
            <Input.TextArea
              value={md}
              onChange={(e) => setMd(e.target.value)}
              autoSize={true}
              style={{ minHeight: '100%', resize: 'none' }}
            />
          </div>
        )}
        <div className={styles.preview}>
          {loading ? null : !md ? <TRDefault type="empty" /> : <ReactMarkdown>{md}</ReactMarkdown>}
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  buttonPermissions: global?.configure?.buttonPermissions,
}))(UpdateLog);
